<template>
  <el-alert title="你已经是优惠卷的会员，不能重复领取" v-show="showalert" type="warning" />
    <div class="common-layout">
      <el-container>
        <el-header>
          <h5 class="mb-2">  <el-page-header :icon="null" @back="routers.push('/index')">

          <template #content>
            <div class="flex items-center">
              <el-avatar
                  :size="32"
                  class="mr-3"
                  src="https://c-ssl.duitang.com/uploads/item/202005/26/20200526091047_Luu45.jpeg"
              />
              <el-select v-model="select" placeholder="菜品筛选" style="width: 115px" class="menu-select" @change="selectRouter()">
                <el-option label="销量优先" value=1 />
                <el-option label="好评优先" value=2 />

              </el-select>
              <el-input
                  v-model="input"
                  style="width: 240px"
                  placeholder="请输入菜名"
                  clearable
                  class="food-search"
              />
              <el-button type="warning" round @click="searchRouter" >搜索</el-button>
            </div>
          </template>
          <template #extra>
            <div class="flex items-center">
              <el-button type="primary" :icon="Edit" circle @click="showcomments()" />
              <el-button type="info" :icon="Message" circle  @click="getmanagemessage()"/>
              <el-button type="success"  @click="handleCommentClick">领取优惠卷</el-button>
              <el-button type="danger" @click="showOrderedItems">已点菜品</el-button>
              <el-button type="primary"  @click="showorderedlist">我的订单</el-button>
            </div>
          </template>
        </el-page-header>
        </h5></el-header>
        <el-container>
          <el-aside width="200px"> <el-col :span="12">

            <el-menu
                active-text-color="#ffd04b"
                background-color="#a43145"
                class="el-menu-vertical-demo"
                default-active="2"
                text-color="#fff"
                @open="handleOpen"
                @close="handleClose"
            >
              <el-sub-menu index="1">
                <template #title>
                  <el-icon><location /></el-icon>
                  <span>菜单</span>
                </template>
                <el-menu-item index="1-1" @click="routerto('/orderfood/recommenditem')"><router-link to="/orderfood/recommenditem" class="menu-router" >为你推荐</router-link></el-menu-item>
                <el-menu-item index="1-2" @click="routerto('/orderfood/specialmenu')"><router-link to="/orderfood/specialmenu" class="menu-router">特价菜</router-link></el-menu-item>
                <el-menu-item index="1-3" @click="routerto('/orderfood/packitem')"><router-link to="/orderfood/packitem" class="menu-router">特色套餐</router-link></el-menu-item>
                <el-menu-item index="1-4" @click="routerto('/orderfood/colddish')"><router-link to="/orderfood/colddish" class="menu-router">凉菜</router-link></el-menu-item>
                <el-menu-item index="1-5" @click="routerto('/orderfood/hotfood')"><router-link to="/orderfood/hotfood" class="menu-router">热菜</router-link></el-menu-item>
                <el-menu-item index="1-7" @click="routerto('/orderfood/meat')"><router-link to="/orderfood/meat" class="menu-router">肉类</router-link></el-menu-item>
                <el-menu-item index="1-8" @click="routerto('/orderfood/seafood')"><router-link to="/orderfood/seafood" class="menu-router">海鲜肉类</router-link></el-menu-item>
                <el-menu-item index="1-9" @click="routerto('/orderfood/staple')"><router-link to="/orderfood/staple" class="menu-router">主食</router-link></el-menu-item>
                <el-menu-item index="1-10" @click="routerto('/orderfood/drink')"><router-link to="/orderfood/drink" class="menu-router">酒水</router-link></el-menu-item>
                <el-menu-item index="1-11" @click="routerto('/orderfood/soup')"><router-link to="/orderfood/soup" class="menu-router">汤羹</router-link></el-menu-item>
              </el-sub-menu>

            </el-menu>
          </el-col></el-aside>
          <el-main><router-view></router-view></el-main>
        </el-container>
      </el-container>
    </div>

  <el-dialog
      title="领取优惠卷"
      v-model="dialogVisible"
      width="30%"
      :before-close="closediglog"
  >
    <el-form>
<span class="span-title">优惠券(一人只能领取一张相同的卷)</span>
      <div v-for="(coupon,index) in coupons " :key="index"  class="coupon-item" >
        <div>

          <span  class="span-coupon-name">{{coupon.member}}可领取一张</span>

        </div>
        <span class="span-coupon-description">{{coupon.description}}</span>

        <div>

         <span class="span-coupon-number">
           剩余卷量:
         </span>
          <el-progress
              :text-inside="true"
              :stroke-width="24"
              :percentage="coupon.number"
              :color="colors"
          />
<span class="span-coupon-validity">
  有效期：{{coupon.startDate}}------{{coupon.endDate}}
</span>
        </div>


        <div><el-button :type="coupon.buttontype" @click="handleCancel(coupon)" :disabled="coupon.ismember" >{{coupon.button}}</el-button></div>
      </div>
    </el-form>
    <span slot="footer" class="dialog-footer">

    </span>
  </el-dialog>

  <el-dialog
      title="订单消息通知"
      v-model="showmessage"
      width="30%"
  >
<span class="redismessage">
  {{Redismessage}}
</span>
<el-button type="primary" @click="showmessage=false">知道了</el-button>
  </el-dialog>


  <el-dialog
      title="活动通知"
      v-model="showdiscountmessage"
      width="30%"
  >
<span class="redismessage">
  {{discountmessage}}
</span>
    <el-button type="primary" @click="showdiscountmessage=false">知道了</el-button>
  </el-dialog>
  <el-dialog
      title="优惠卷发放通知通知"
      v-model="dialogVisible2"
      width="30%"
  >
<span class="redismessage">
  {{couponmessage}}
</span>
    <el-button type="primary" @click="dialogVisible2=false">知道了</el-button>
  </el-dialog>


  <el-dialog
      title="我的评论"
      v-model="showcomment"
      width="30%"
  >
    <el-table :data="currentPageItems" >
      <el-table-column
              prop="comment"
              label="评论"
              width="100"
      >
      </el-table-column>
      <el-table-column
              prop="rating"
              label="评分"
              width="100"
      >
      </el-table-column>
      <el-table-column
              prop="commentTime"
              label="评论时间"
              width="100"
      >
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="120" >
        <template #default="{row}">
          <el-button link type="primary" size="small" class="el-button1" @click="getcommentReplyList(row.id)">回复我的</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        small
        background
        layout="prev, pager, next"
        :total="totalItems"
        :page-size="pageSize"
        v-model:currentPage="currentPage"
        class="mt-4"
    />
  </el-dialog>
  <el-dialog
      title="回复我的"
      v-model="showreplycomment"
      width="30%"
  >
    <el-table :data="replycomment" >
      <el-table-column
          prop="comment"
          label="评论"
          width="100"
      >
      </el-table-column>
      <el-table-column
          prop="rating"
          label="评分"
          width="100"
      >
      </el-table-column>
      <el-table-column
          prop="commentTime"
          label="评论时间"
          width="100"
      >
      </el-table-column>
    </el-table>
  </el-dialog>
</template>

<script  setup>

import {computed, h, onMounted, reactive, ref, unref} from 'vue'
import {
  findallcouponsservice, getcommentListService, getcommentReplyListService, getcouponmessageService,
  getcouponsservice, getdiscountpricemessageservice,
  getmanagemessageservice,
  getordersevice,
  getuserallroleservice
} from "@/api/food.js";
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
} from '@element-plus/icons-vue'
import {useRouter} from 'vue-router'
import router from "@/router.js";
import {ElMessage, ElNotification} from "element-plus";
const showalert=ref(false)
const showreplycomment=ref(false)
const items = reactive([]);
const input = ref('')
const visible = ref(false)
const popoverRef = ref()
const showmessage=ref(false)
const routers=useRouter();
const dialogVisible = ref(false);
const select=ref('');
const showcomment=ref(false)
const coMmentList=reactive([])
const coupons=reactive([])
const replycomment=reactive([])
const button = ref("领取")
const dialogVisible2=ref(false)
const Redismessage=ref('')
const currentPage = ref(1); // 当前页数
const pageSize = ref(10);
const couponmessage=ref('')
const discountmessage=ref('')
const showdiscountmessage=ref(false)
const showOrderedItems = async () => {
await router.push("/orderfood/orderList")
};
const searchRouter=async ()=>{
  await routers.push({
    path:'/orderfood/searchfood',
    query: {
      input:input.value,
    }
  })
}
const routerto = async (paths) => {
 await routers.push({path: paths})
}
const showorderedlist = async () => {
  await router.push("/orderfood/orderedList")
};

const handleCommentClick = () => {
  dialogVisible.value = true;

};
const closediglog = () => {
  dialogVisible.value = false;

};
const showcomments = () => {
  showcomment.value=true
}
const handleCancel= async (coupon)=> {
  const response=await getcouponsservice(coupon.id)
  if(response.code === 200){
    coupon.button="已领取"

    coupon.number=coupon.number-1
    coupon.ismember=true
    coupon.buttontype="info"
    console.log(coupon)
    ElNotification({
      title: 'Title',
      message: h('i', { style: 'color: teal' }, '领取优惠卷成功'),
    })
    dialogVisible.value = false;
  }else {
    dialogVisible.value = false;
    showalert.value=true
    ElNotification({
      title: 'Title',
      message: h('i', { style: 'color: red' }, '领取优惠卷失败，你已经领取过请勿重复领取'),
    })
    console.log("领取失败")
  }

}
const getallcoupons =async () => {
  const response=await findallcouponsservice()
  if(response.code === 200){
    response.date.forEach(coupon => {
      if(coupon.number>0){
          coupon.startDate=formatDateTime(coupon.startDate)
          coupon.endDate=formatDateTime(coupon.endDate)
        }
      coupon.ismember=true
      coupon.buttontype="success"
      coupon.button="领取"
          coupons.push(coupon)
          console.log(coupon)
        }
    )
    console.log(coupons)
  }else {
    console.log("获取优惠卷失败")
  }
}
const getuserallrole =async () => {
const response = await getuserallroleservice()
  if ( response.code === 200){
    response.date.forEach(role => {
      coupons.forEach(coupon => {
        if(coupon.member===role.roleName){
          if(coupon.number>0){
            coupon.ismember=false
            console.log("分支对比:"+coupon.member+"=="+role.roleName)
            coupon.buttontype="primary"
          }

        }

      })
    })

  }else {

  }

}
onMounted(()=>{
  getallcoupons()
  getuserallrole()
  getdiscountpricemessage()
  geticouponmessage()
  getmyComment()
})
const colors = [
  { color: '#f56c6c', percentage: 20 },
  { color: '#e6a23c', percentage: 40 },
  { color: '#5cb87a', percentage: 60 },
  { color: '#5cb87a', percentage: 80 },
  { color: 'green', percentage: 100 },
]
const formatDateTime = (dateTimeStr) => {
  const date = new Date(dateTimeStr);
  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`;
};

const selectRouter=async ()=>{
  await routers.push({
    path:'/orderfood/selectOrder',
    query: {
      type:select.value,
    }
  })
}
const getmanagemessage=async ()=>{
  const response=await getmanagemessageservice()
  if(response.code === 200){
    Redismessage.value=response.date
    showmessage.value=true
  }else {
    ElMessage.error( "获取消息失败")
  }
}

const getdiscountpricemessage = async () => {
  const response=await getdiscountpricemessageservice()
  if(response.code === 200){
    if(response.date===null){
      showdiscountmessage.value=true
      discountmessage.value="暂无活动信息"
    }
    else {
      showdiscountmessage.value=true
      discountmessage.value=response.date
    }

  }else {
    ElMessage.error( "获取消息失败")
  }
}

const geticouponmessage = async () => {
  const response=await getcouponmessageService()
  if(response.code === 200){
    if(response.date===null){
      couponmessage.value="暂无优惠卷信息"
    }
    couponmessage.value=response.date
    dialogVisible2.value=true
  }else {
    ElMessage.error( "获取消息失败")
  }

}
const currentPageItems = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;
  return coMmentList.slice(startIndex, endIndex);
});
const totalItems = computed(() => coMmentList.length);


const getmyComment = async () => {
  const response=await getcommentListService()
  if(response.code === 200){
    coMmentList.splice(0, coMmentList.length); // 清空原有数据
    response.date.forEach(comment => {
      if(comment.reply===null){
        comment.reply="暂无回复"
      }
      comment.commentTime=formatDateTime(comment.commentTime)
      coMmentList.push(comment)
    })
    console.log(coMmentList)
    ElMessage.success("获取评论成功")
  }else {
    ElMessage.error( "获取评论失败")
  }
}

const getcommentReplyList =async (id) => {
  const response=await getcommentReplyListService(id)
  showreplycomment.value=true
  replycomment.splice(0, coMmentList.length);
  if(response.code === 200){
    replycomment.splice(0, replycomment.length); // 清空原有数据
    response.date.forEach(comment => {
      comment.commentTime=formatDateTime(comment.commentTime)
      replycomment.push(comment)
    })
    console.log(replycomment)
    ElMessage.success("获取我的回复评论成功")
  }else {
    ElMessage.error( "获取我的回复评论失败")
  }
}
</script>

<style scoped>
.el-menu-vertical-demo{
  width: 200px;
  left: 0;
}
.food-search {
  margin-left: 350px;
}
.el-popover__popper{

  transform: translateX(-400px);
}
.card-price{
  color: red;
}
.el-popover__popper {
  max-height: 90vh; /* 例如：最大高度为页面高度的90% */
}
.menu-router {
  color: white;
  text-decoration: none; /* 取消下划线 */

}
.menu-select{
left: 350px;
}
.span-title{
  font-size: 20px;
  font-weight: bold;
  color: #a43145;
  margin-bottom: 10px;
  margin-top: 10px;
  margin-left: 10px;
  margin-right: 10px;
  display: block;
}
.span-coupon-description{
  font-size: 15px;
  font-weight: bold;
  color: burlywood;
  margin-bottom: 10px;
}
.span-coupon-number{



  font-size: 15px;
  font-weight: bold;
  color: rosybrown;
}
.span-coupon-validity{
  font-size: 15px;
  font-weight: bold;
  color: brown;
}
.coupon-item{
  margin-bottom: 10px;
  margin-left: 10px;
  margin-right: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 10px;
  background-color: #f5f5f5;
}
.span-coupon-name{
  font-size: 20px;
  font-weight: bold;
  color: #a43145;
}
.redismessage{
  color: black;
  font-size: 15px;
  font-weight: bold;
  margin-left: 10px;
  margin-right: 10px;
  margin-top: 5px;
  margin-bottom: 10px;
  display: block;
  text-align: center;
}
</style>